package com.ruoyi.point.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.point.domain.ExchangeOrder;
import com.ruoyi.point.service.IExchangeOrderService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 兑换订单Controller
 * 
 * @author hy
 * @date 2025-08-12
 */
@RestController
@RequestMapping("/point/order")
public class ExchangeOrderController extends BaseController
{
    @Autowired
    private IExchangeOrderService exchangeOrderService;

    /**
     * 查询兑换订单列表
     */
    @PreAuthorize("@ss.hasPermi('point:exchangeOrder:list')")
    @GetMapping("/list")
    public TableDataInfo list(ExchangeOrder exchangeOrder)
    {
        startPage();
        List<ExchangeOrder> list = exchangeOrderService.selectExchangeOrderList(exchangeOrder);
        return getDataTable(list);
    }

    /**
     * 导出兑换订单列表
     */
    @PreAuthorize("@ss.hasPermi('point:exchangeOrder:export')")
    @Log(title = "兑换订单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(ExchangeOrder exchangeOrder)
    {
        List<ExchangeOrder> list = exchangeOrderService.selectExchangeOrderList(exchangeOrder);
        ExcelUtil<ExchangeOrder> util = new ExcelUtil<ExchangeOrder>(ExchangeOrder.class);
        return util.exportExcel(list, "兑换订单数据");
    }

    /**
     * 获取兑换订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('point:exchangeOrder:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(exchangeOrderService.selectExchangeOrderById(id));
    }

    /**
     * 新增兑换订单
     */

    @Log(title = "兑换订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ExchangeOrder exchangeOrder)
    {
        return toAjax(exchangeOrderService.insertExchangeOrder(exchangeOrder));
    }

    /**
     * 创建兑换订单（包含积分扣减和流水记录）
     */
    //@PreAuthorize("@ss.hasPermi('point:exchangeOrder:create')")
    @Log(title = "创建兑换订单", businessType = BusinessType.INSERT)
    @PostMapping("/create")
    public AjaxResult createOrder(@RequestBody ExchangeOrder exchangeOrder)
    {
        try {
            return success(exchangeOrderService.createExchangeOrderWithPointDeduction(exchangeOrder));
        } catch (Exception e) {
            return error("创建订单失败：" + e.getMessage());
        }
    }

    /**
     * 修改兑换订单
     */
    @PreAuthorize("@ss.hasPermi('point:exchangeOrder:edit')")
    @Log(title = "兑换订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ExchangeOrder exchangeOrder)
    {
        System.out.println("收到更新请求，订单ID: " + exchangeOrder.getId());
        System.out.println("更新状态: " + exchangeOrder.getStatus());
        System.out.println("更新数据: " + exchangeOrder.toString());
        
        int result = exchangeOrderService.updateExchangeOrder(exchangeOrder);
        System.out.println("更新结果: " + result);
        
        return toAjax(result);
    }

    /**
     * 删除兑换订单
     */
    @PreAuthorize("@ss.hasPermi('point:exchangeOrder:remove')")
    @Log(title = "兑换订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(exchangeOrderService.deleteExchangeOrderByIds(ids));
    }

    /**
     * 根据ID查询兑换订单详情（多表联查）
     */
    @GetMapping("/detail/{id}")
    public AjaxResult getDetail(@PathVariable("id") Long id)
    {
        return success(exchangeOrderService.selectExchangeOrderDetailById(id));
    }

    /**
     * 查询所有兑换订单详情（多表联查）
     */
    @GetMapping("/all-details")
    public AjaxResult getAllDetails()
    {
        return success(exchangeOrderService.selectAllExchangeOrderDetails());
    }

    /**
     * 查询用户兑换订单历史列表（多表联查）
     */
    @GetMapping("/history/{userId}")
    public AjaxResult getUserHistory(@PathVariable("userId") Long userId)
    {
        return success(exchangeOrderService.selectExchangeOrderHistoryByUserId(userId));
    }

    /**
     * 查询兑换订单历史列表（多表联查，支持分页和筛选）
     */
    @GetMapping("/history/list")
    public TableDataInfo getHistoryList(ExchangeOrder exchangeOrder)
    {
        startPage();
        List<ExchangeOrder> list = exchangeOrderService.selectExchangeOrderHistoryList(exchangeOrder);
        return getDataTable(list);
    }

    /**
     * 查询所有处理中的订单（多表联查，用于物流管理）
     */
    @GetMapping("/processing")
    public AjaxResult getProcessingOrders()
    {
        return success(exchangeOrderService.selectProcessingOrders());
    }
}
